<?php

namespace App\Imports\Area;

use App\Kuafu\Shop\Model\AreaModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class AreaGradeImport implements ToCollection
{
    public static Command $command;

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $successCount = $failCount = 0;
        $passId       = [];
        $collection->each(function ($row, $index) use (&$successCount, &$failCount, &$passId) {
            if (isset($row[2]) && $row[2]) {
                $likeStr  = str_replace("市", "", $row[1]);
                $areaInfo = AreaModel::query()
                                     ->where("cnFullName", "like", "{$likeStr}%")
                                     ->where("level", 2)
                                     ->get();

                switch ($existCount = $areaInfo->count()) {
                    case 1:
                        $area            = $areaInfo->getIterator()->current();
//                        $area->grade     = $this->getGradeByContent($row[2]);
                        $area->menuLevel = $this->getMenuLevelByContent($row[2]);
                        $area->save();
                        $successCount++;
                        if (in_array($area->id, $passId)) {
                            self::$command->getOutput()->writeln($area->id);
                        } else {
                            array_push($passId, $area->id);
                        }
                        break;
                    default:
                        self::$command->getOutput()->writeln($areaInfo->toJson(JSON_UNESCAPED_UNICODE));
                        self::$command->getOutput()->writeln(json_encode([
                            "index" => $index,
                            "count" => $existCount
                        ]));
                        $failCount++;
                        break;
                }
            }
        });

        self::$command->getOutput()->writeln(json_encode([
            "successCount" => $successCount,
            "failCount"    => $failCount
        ]));
    }


    /**
     * @param string $content
     * @return int
     */
    public function getGradeByContent(string $content): int
    {
        return [
            "一线城市"  => 1,
            "新一线城市" => 1,
            "二线城市"  => 2,
            "三线城市"  => 3,
            "四线城市"  => 4,
            "五线城市"  => 5,
        ][$content];
    }

    /**
     * 菜单等级
     * @param string $content
     * @return string
     */
    public function getMenuLevelByContent(string $content): string
    {
        return [
            'A级' => 'A',
            'B级' => 'B',
            'C级' => 'C',
            '西藏价' => '西藏价',
        ][$content];
    }
}
